package com.fangzhi.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {  
  
    private static final String KEY = "1234567890123456"; // 16个字符，128位  

    /**
     * 密碼加密
     * @param strToEncrypt
     * @return
     */
    public static String encrypt(String strToEncrypt) {  
        try {  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");  
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);  
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));  
        } catch (Exception e) {  
            System.out.println("Error while encrypting: " + e.toString());  
        }  
        return null;  
    }

    /**
     * 密碼解密
     * @param strToDecrypt
     * @return
     */
    public static String decrypt(String strToDecrypt) {  
        try {  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");  
            cipher.init(Cipher.DECRYPT_MODE, secretKey);  
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));  
        } catch (Exception e) {  
            System.out.println("Error while decrypting: " + e.toString());  
        }  
        return null;  
    }

    public static void main(String[] args) {
        final String originalString = "18739933311";
        final String encryptedString = AESUtil.encrypt(originalString);
        final String decryptedString = AESUtil.decrypt(encryptedString);

        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}